<template>
    <el-form :model="formData" :rules="formRules" ref="formRef" size="small" :inline="false" label-width="100px">
      <el-row style="margin-bottom: 18px">
        <el-col :span="12">
          <el-form-item label="报价主题" prop="title">
            <el-input v-model="formData.title" maxlength="64" clearable placeholder="请填写报价主题"/>
          </el-form-item>
          <el-form-item label="报价单位" prop="supplierInfoId">
            <el-select v-model="formData.supplierInfoId" placeholder="请选择报价单位" clearable filterable @change="supplierChange">
              <el-option v-for="item in supplierList" :key="item.supplierInfoId" :value="item.supplierInfoId" :label="item.shortName"/>
            </el-select>
          </el-form-item>
          <el-form-item label="报价金额" prop="amount">
            <el-input-number v-model="formData.amount" placeholder="请填写报价金额" style="width: 200px" :max="99999999" :min="0" :precision="2" :controls="false"/>
            <el-checkbox style="margin-left: 10px" v-model="formData.amountTax" label="是否含税" :true-label="1" :false-label="0" size="small"/>
          </el-form-item>
          <el-form-item label="报价日期" prop="quoteDate">
            <el-date-picker v-model="formData.quoteDate" type="date" placeholder="请选择报价日期" size="small" value-format="YYYY-MM-DD"/>
          </el-form-item>
          <el-form-item label="运输说明" prop="transportExplain">
            <el-input v-model="formData.transportExplain" placeholder="请填写运输说明" clearable/>
          </el-form-item>
          <el-form-item label="包装说明" prop="packageExplain">
            <el-input v-model="formData.packageExplain" placeholder="请填写包装说明" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报价单号" prop="quoteNo">
            <el-input v-model="formData.quoteNo" maxlength="64" clearable placeholder="请填写报价单号"/>
          </el-form-item>
          <el-form-item label="报价人" prop="contactUserId">
            <el-select v-model="formData.contactUserId" :placeholder="formData.supplierInfoId ? '请选择报价人' : '请先选择报价单位'" @change="contactChange" clearable filterable>
              <el-option v-for="item in contactList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请填写联系电话" clearable maxlength="16"/>
          </el-form-item>
          <el-form-item label="结款方式" prop="paymentType">
            <el-select v-model="formData.paymentType" placeholder="请选择结款方式" clearable filterable>
              <el-option v-for="item in dictMap['PaymentType']" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="交付说明" prop="submitExplain">
            <el-input v-model="formData.submitExplain" placeholder="请填写交付说明" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3"/>
      </el-form-item>
      <el-divider/>
      <el-form-item label="产品清单">
        <el-table :data="formData.productItems" stripe height="240" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}" border>
          <el-table-column label="序号" type="index" max-width="75"/>
          <el-table-column label="产品名称" max-width="150" prop="name">
            <template v-slot="{row}">
              <el-select v-model="row.name" allow-create filterable default-first-option clearable>
                <el-option v-for="item in productNames" :key="item.id" :value="item.name" :label="item.name"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="型号" max-width="150" prop="ver">
            <template v-slot="{row}">
              <el-input v-model="row.ver" maxlength="64" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="详情/规格" max-width="150" prop="specification">
            <template v-slot="{row}">
              <el-input v-model="row.specification" maxlength="255" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="数量" max-width="100" prop="num">
            <template v-slot="{row}">
              <el-input-number v-model="row.num" :min="0" :max="999999" :controls="false" style="width: 90px" @change="calAmount(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="价格" max-width="130" prop="price">
            <template v-slot="{row}">
              <el-input-number v-model="row.price" :min="0" :max="999999" :controls="false" :precision="2" style="width: 120px" @change="calAmount(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="小计" max-width="140" prop="total"/>
          <el-table-column label="备注" prop="remark">
            <template v-slot="{row}">
              <el-input v-model="row.remark" type="textarea" :rows="2"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" max-width="90">
            <template v-slot="{$index, row}">
              <el-button type="danger" :icon="Delete" text @click="removeProduct($index, row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 5px;width: 100%">
          <el-col :span="3" :offset="1">
            <el-button type="primary" :icon="Plus" @click="addProduct" text>添加</el-button>
          </el-col>
          <el-col :span="5">合计：{{ formData.productAmountSum }} 元</el-col>
          <el-col :span="6">大写：{{ numToChinese(formData.productAmountSum) }}</el-col>
        </el-row>
      </el-form-item>
    </el-form>
</template>

<script>
// 报价单 QUOTATION_ORDER
import {computed, reactive, ref, toRefs, watch, nextTick, onMounted} from 'vue'
import {getSupplierSelector} from '/@/api/supplier'
import purchaseOrderApi from '/@/api/supplier/purchaseOrder'
import {createQuote, editQuote} from '/@/api/supplier/quoteOrder'
import {getDictByCodes} from '/@/api/sys/dict'
import {numToChinese} from '/@/utils/common'
import {Plus, Delete} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {getContactList} from '/@/api/supplier/supplierContact'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'QuotationOrderForm',
    props: {
        code: {
            type: String,
            default: ''
        },
        supplierId: {   // 供应商信息id
            type: String,
            default: null
        },
        editForm: {
            type: Object,
            default: () => {
              return {}
            } 
        },
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props, context) {
        const formRef = ref()
        const {code, supplierId, editForm, selectTime, editId} = toRefs(props)
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            formData: {
                tempId: 0,
                title: null,
                type: 'QUOTATION_ORDER',
                quoteNo: null,
                supplierInfoId: null,
                contactUserId: null,
                contactPhone: null,
                amount: null,
                productAmountSum: null,
                amountTax: null,  // 是否含税 0不含 1含
                paymentType: null,  // 结款方式 字典 PaymentType
                quoteDate: selectTime.value,  // 报价日期
                submitExplain: null,  // 交付说明
                transportExplain: null, // 运输说明
                packageExplain: null,   // 包装说明
                remark: null,   // 描述
                productItems: [],   // 产品详情
                matter: 0   // 是否加到事项, 0否 1是
            },
            formRules: {
                title: {required: true, message: '请填写报价单主题', trigger: 'blur'},
                supplierInfoId: {required: true, message: '请选择报价单位', trigger: 'change'}
            },
            dictMap: {},
            productNames: [],   // 产品名称列表
            supplierList: [],   // 用户供应商列表
            contactList: [],  // 供应商联系人列表
            getCode: false,
            originForm: {}
        })
        const checkCode = computed(() => {
            let flag = code.value == state.formData.type
            if (flag) {
                // if (editForm.value) {
                //     state.formData = Object.assign({}, editForm.value)
                // } else {
                //     resetForm()
                // }
                if (supplierId) {
                    state.formData.supplierInfoId = supplierId.value
                }
                getDictByCodes(['PaymentType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
                // 获取供应商列表
                getSupplierSelector().then(res => state.supplierList = res.data).catch(e => console.log(e))
                // 商品名称列表
                purchaseOrderApi.getHistoryProducts().then(res => state.productNames = res.data).catch(e => console.log(e))
            }
            return flag
        })
        const addProduct = () => state.formData.productItems.push({
            id: null,
            name: null,
            ver: null,
            specification: null,
            num: 0,
            price: 0.00,
            total: 0.00,
            remark: null
        })
        // 移除产品行
        const removeProduct = (index, product) => {
            state.formData.productItems.splice(index, 1)
            state.formData.productAmountSum -= product.total
        }
        // 供应商改动
        const supplierChange = (supplierInfoId) => {
            getContactList(supplierInfoId).then(res => {
                state.formData.contactUserId = null
                state.contactList = res.data
            }).catch(e => console.log(e))
        }
        // 联系人改动
        const contactChange = (contactId) => {
            for (let i = 0; i < state.contactList.length; i++) {
                let item = state.contactList[i]
                if (item.id == contactId) {
                state.formData.contactPhone = item.phone
                break
                }
            }
        }
        // 产品合计
        const calAmount = (product) => {
            let total = 0
            product.total = ((product.num || 0) * (product.price || 0)).toFixed(2)
            state.formData.productItems.forEach(item => total += (item.num || 0) * (item.price || 0))
            state.formData.productAmountSum = total.toFixed(2)
        }
        const submit = (type) => {
            if(!formRef) return;
            return new Promise((resolve, reject) => {
                formRef.value.validate(async (valid) => {
                    if(!valid) {
                        return false
                    }
                    state.formData.matter = type
                    let res
                    if (editId.value) {
                        res = await editQuote(state.formData)
                    } else {
                        res = await createQuote(state.formData)
                    }
                    if (res.code == 0) {
                        ElMessage.success((type == 0 ? '保存' : '提交') + '成功！')
                        resolve()
                        reset()
                    }else{
                        reject()
                    }
                })
            })
        }
        const reset = () => {
            if (!formRef) return;
            formRef.value.resetFields();
        }
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                state.formData.id = editId.value
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
              })
            }
          }        
        )
        onMounted(() => {
            state.getCode = checkCode.value
        })
        return{
            ...toRefs(state),
            formRef,
            Plus,
            Delete,
            addProduct,
            removeProduct,
            supplierChange,
            contactChange,
            calAmount,
            submit,
            reset,
            numToChinese
        }
    }
}
</script>

<style>

</style>